package com.bigstar.lolen_e;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.content.res.AssetManager.AssetInputStream;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.ads.AdRequest;
import com.google.ads.AdView;

public class Champion extends Activity implements OnClickListener{
	
	private MediaPlayer fileOfMusic;
	private int champId;
	private String skillmovie[] = new String[6];
	private ArrayList<SkinData> arrSkin;
	boolean skin_dialog = false;
	
	private int skinId = -1;
	private String tip;
	private String tip2;
	private String skill_name[] = new String[5];
	private String skill_text[] = new String[5];
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_VOLUME_UP){
			AudioManager audio = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
			int volume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
			audio.setStreamVolume(AudioManager.STREAM_MUSIC, ++volume, AudioManager.FLAG_SHOW_UI);	
			return true;
		}else if(keyCode == KeyEvent.KEYCODE_VOLUME_DOWN){
			AudioManager audio = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
			int volume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
			audio.setStreamVolume(AudioManager.STREAM_MUSIC, --volume, AudioManager.FLAG_SHOW_UI);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
    
	@Override 
	public void onCreate(Bundle savedInstanceState) { 
		super.onCreate(savedInstanceState); 
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        ChampionData.load(this);
        ItemData.load(this);
        Rune.load(this);
		setContentView(R.layout.champion); 
        AdView adview = (AdView)findViewById(R.id.adView);
        AdRequest re = new AdRequest(); 
        adview.loadAd(re);
 		if(getIntent().getExtras() != null){
 			champId = Integer.parseInt(getIntent().getExtras().getString("champId"));
 		}
		
		loadStat();
        loadSkill();
        
		SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
        if(pref.getBoolean("sound", true)){
            fileOfMusic = null;
            AssetFileDescriptor afd = null;
    		try {
    			afd = getAssets().openFd("sound/"+ChampionData.champions.get(champId).name_en+".mp3");
    			if(afd != null){
    		        fileOfMusic = new MediaPlayer();
    		        fileOfMusic.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
    		        fileOfMusic.prepare();
    		        afd.close();	
    			}
    		} catch (IOException e) {
    			e.printStackTrace();
    		}finally{
    			try {
    				if(afd != null)
    					afd.close();
    			} catch (IOException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		}
    		
            fileOfMusic.start();	
        }
	}
	
	public void loadStat(){
		ImageView iv = (ImageView) findViewById(R.id.char_img);
		String path = "champ_img/"+ChampionData.champions.get(champId).name_en+".jpg";
		try {
			iv.setImageDrawable(Drawable.createFromStream(getAssets().open(path),"src"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		iv.setOnClickListener(this);
		iv = (ImageView) findViewById(R.id.history);
		iv.setOnClickListener(this);
        TextView tv = (TextView) findViewById(R.id.char_name_en);
        tv.setText(ChampionData.champions.get(champId).name_en);
        
        tv = (TextView) findViewById(R.id.char_nickname);
        tv.setText(ChampionData.champions.get(champId).nick_name);
        
        tv = (TextView) findViewById(R.id.char_tags);
        tv.setText("Tag : "+ChampionData.champions.get(champId).tags);
        
        tv = (TextView) findViewById(R.id.rp_point);
        tv.setText(""+ChampionData.champions.get(champId).rp_point);
        
        tv = (TextView) findViewById(R.id.ip_point);
        tv.setText(""+ChampionData.champions.get(champId).ip_point);
        int grp[] = {0,0,0,0};
        StringTokenizer st = new StringTokenizer(ChampionData.champions.get(champId).stat, ";");
        for(int i = 0; i < 4; i++){
        	grp[i] = Integer.parseInt(st.nextToken());
        }
		iv = (ImageView) findViewById(R.id.attack_grp);
        iv.setImageResource(R.drawable.attack_01 + grp[1] - 1);
        
		iv = (ImageView) findViewById(R.id.spells_grp);
        iv.setImageResource(R.drawable.spells_01 + grp[2]  - 1);
        
		iv = (ImageView) findViewById(R.id.health_grp);
        iv.setImageResource(R.drawable.health_01 + grp[0]  - 1);
        
		iv = (ImageView) findViewById(R.id.difficulty_grp);
        iv.setImageResource(R.drawable.diff_01 + grp[3]  - 1);
        
        
        String stat;
        stat = ChampionData.champions.get(champId).damage+"\r\n";
        stat = stat+ChampionData.champions.get(champId).health+"\r\n";
        stat = stat+ChampionData.champions.get(champId).mana+"\r\n";
        stat = stat+ChampionData.champions.get(champId).attack_speed+"\r\n";
        stat = stat+ChampionData.champions.get(champId).move_speed+"\r\n";
        stat = stat+ChampionData.champions.get(champId).range+"\r\n";
        stat = stat+ChampionData.champions.get(champId).armor+"\r\n";
        stat = stat+ChampionData.champions.get(champId).mr+"\r\n";
        stat = stat+ChampionData.champions.get(champId).health_regen+"\r\n";
        stat = stat+ChampionData.champions.get(champId).mana_regen;
        tv = (TextView) findViewById(R.id.init_stat);
        tv.setText(stat);
        
        stat = "(+"+ChampionData.champions.get(champId).damage_per_level+"/level)\r\n";
        stat = stat+"(+"+ChampionData.champions.get(champId).health_per_level+"/level)\r\n";
        stat = stat+"(+"+ChampionData.champions.get(champId).mana_per_level+"/level)\r\n";
        stat = stat+"(+"+ChampionData.champions.get(champId).attack_speed_per_level+"/level)\r\n";
        stat = stat+"\r\n";
        stat = stat+"\r\n";
        stat = stat+"(+"+ChampionData.champions.get(champId).armor_per_level+"/level)\r\n";
        stat = stat+"(+"+ChampionData.champions.get(champId).mr_per_level+"/level)\r\n";
        stat = stat+"(+"+ChampionData.champions.get(champId).health_regen_per_level+"/level)\r\n";
        stat = stat+"(+"+ChampionData.champions.get(champId).mana_regen_per_level+"/level)";
        tv = (TextView) findViewById(R.id.lvlup_stat);
        tv.setText(stat);
	}
	
	public void loadSkill(){
		TextView tv;
		ImageView iv;
		String path;
		StringTokenizer st;
        st = null;
        int getResId;
        st = new StringTokenizer(ChampionData.champions.get(champId).skill_movie, ";");
        for(int i = 0; i < 6; i++){
        	skillmovie[i] = st.nextToken();
        }
		
		AssetManager assetManager = Champion.this.getResources().getAssets();
		AssetInputStream ais;
		int skill_index = 0;
		try {
			ais = (AssetInputStream)assetManager.open("skill_text/"+ChampionData.champions.get(champId).name_en+".txt");
	        BufferedReader br = new BufferedReader(new InputStreamReader(ais));
	        String line;
	        while((line=br.readLine()) != null){
	        	if(skill_index < 5){
	        		skill_name[skill_index] = line;
	        	}else{
	        		skill_text[skill_index-5] = line;
	        	}
	        	skill_index++;
	        }
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} 
		String[] skills = {"(Passive)", "(Q)", "(W)", "(E)", "(R)"};
		for(int i = 0; i < skills.length; i++){
			getResId = getResources().getIdentifier("skill_"+i, "id", "com.bigstar.lolen_e");
	        iv = (ImageView) findViewById(getResId);
	        path = "skill_img/"+ChampionData.champions.get(champId).name_en+"_"+i+".jpg";
			try {
				iv.setImageDrawable(Drawable.createFromStream(getAssets().open(path),"src"));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			iv.setOnClickListener(this);
			getResId = getResources().getIdentifier("skill_"+i+"_name", "id", "com.bigstar.lolen_e");
	        tv = (TextView) findViewById(getResId);
	        tv.setText(skill_name[i]+" "+skills[i]);
	        getResId = getResources().getIdentifier("skill_"+i+"_text", "id", "com.bigstar.lolen_e");
	        tv = (TextView) findViewById(getResId);
	        tv.setText(Html.fromHtml(skill_text[i]));
		}
	}

	@Override
	public void onClick(View v) {
		if(v.getId() >= R.id.skill_0 && v.getId() <= R.id.skill_4){
			int i = (v.getId() - R.id.skill_0) / 3 + 1; 
			if(!skillmovie[i].equals("x")){
				Intent intent = new Intent(Intent.ACTION_VIEW);
				Uri uri = Uri.parse("http://d28xe8vt774jo5.cloudfront.net/abilities/videos/"+skillmovie[0]+"_"+skillmovie[i]+".mp4");
				intent.setDataAndType(uri,"video/mp4");
				startActivity(intent);	
			}else{
				Toast.makeText(Champion.this, "No Search Movie", Toast.LENGTH_SHORT).show();
			}
		}else if(v.getId() == R.id.history){
			String his = null;
			try {
				his = loadHistory(ChampionData.champions.get(champId).name_en);
				loadTip(ChampionData.champions.get(champId).name_en);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
			HistoryDialog hd = new HistoryDialog(this, ChampionData.champions.get(champId).name_en, ChampionData.champions.get(champId).nick_name, his, tip, tip2);
			hd.show();
		}else{
	 		try {
				loadSkin(this);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			String skins[] = new String[arrSkin.size()];
			for(int i = 0; i < arrSkin.size(); i++){
				skins[i] = arrSkin.get(i).name_en+"("+arrSkin.get(i).price+"RP)";
			}
			skinId = -1;
			new AlertDialog.Builder(this)
			.setTitle("Choose a skin")
			.setPositiveButton("View", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					Utils.skin = null;
					if(skinId == -1){
						Toast.makeText(Champion.this, "Choose a skin", Toast.LENGTH_SHORT).show();
					}else{
						if(skin_dialog){
							return;
						}
						skin_dialog = true;
						Intent intent = new Intent(Champion.this, Champion3D.class);
						intent.putExtra("champName", ChampionData.champions.get(champId).name_en);
						intent.putExtra("skinName", arrSkin.get(skinId).name_en);
						Champion.this.startActivity(intent);
						skin_dialog = false;
					}
				}
			})
			.setNegativeButton("Close", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
				}
			})
			.setSingleChoiceItems(skins, -1, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					skinId = whichButton;
				}
			})
			.create().show();	
		}
	}

	private void loadSkin(Context context) throws IOException {
		if(arrSkin == null){
			arrSkin = new ArrayList<SkinData>();
			AssetManager assetManager = context.getResources().getAssets();
			AssetInputStream ais = (AssetInputStream)assetManager.open("gallery/"+ChampionData.champions.get(champId).name_en+".txt"); 
	        BufferedReader br = new BufferedReader(new InputStreamReader(ais));
	        String line;
	        
	        while((line=br.readLine()) != null){
	            StringTokenizer st = new StringTokenizer(line, ";");
	        	SkinData skin = new SkinData();
	        	skin.name_en = st.nextToken();
	        	skin.name_kor = st.nextToken();
	        	skin.price = st.nextToken();
	        	skin.illust = st.nextToken();
	        	skin.skin = st.nextToken();
	        	arrSkin.add(skin);
	        }
	        ais.close();
	        br.close();
		}
	}
	
	public void loadTip(String name) throws IOException {
		AssetManager assetManager = this.getResources().getAssets();
		AssetInputStream ais = (AssetInputStream)assetManager.open("tip/"+ChampionData.champions.get(champId).name_en+".txt"); 
        BufferedReader br = new BufferedReader(new InputStreamReader(ais));
        String line;
        int i = 0;
        while((line=br.readLine()) != null){
        	if(i == 0){
        		tip = line.replaceAll("\\*", "<br><br>- ");
        		tip = tip.substring(9, tip.length());
        		tip += "<br>";
        	}else{
          		tip2 = line.replaceAll("\\*", "<br><br>- ");
          		tip2 = tip2.substring(8, tip2.length());
        	}
        	i++;
        }
	}
	
	public String loadHistory(String name) throws IOException {
		AssetManager assetManager = this.getResources().getAssets();
		AssetInputStream ais = (AssetInputStream)assetManager.open("history/"+ChampionData.champions.get(champId).name_en+".txt"); 
        BufferedReader br = new BufferedReader(new InputStreamReader(ais));
        String line;
        StringBuilder data = new StringBuilder();
        while((line=br.readLine()) != null){
        	data.append(line);
        	data.append("\r\n");
        }
        return data.toString();
	}
	
    @Override
    protected void onResume() {
        ChampionData.load(this);
        ItemData.load(this);
        Rune.load(this);
    	super.onResume();
    }
    
    @Override
    protected void onStop() {
    	super.onStop();
    	if(fileOfMusic != null){
    		if(fileOfMusic.isPlaying()){
    			fileOfMusic.stop();
    		}
    		fileOfMusic.release();
    		fileOfMusic = null;	
    	}
    }
	
	class SkinData{
		String name_en;
		String name_kor;
		String price;
		String illust;
		String skin;
	}
}